//
//  WBFristPageDataModel.swift
//  weibo
//
//  Created by  郭航 on 16/6/27.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

class WBFristPageDataModel: NSObject {
    
     /// 微博创建时间
    var created_at: String?
    
    var createdStr: String? {
        let dateFormatter = NSDateFormatter()
        
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        
        let date = dateFormatter.dateFromString(created_at ?? "")!
        
        dateFormatter.dateFormat = "yyyy"
        
        //是不是今年
        if dateFormatter.stringFromDate(date) == dateFormatter.stringFromDate(NSDate()) {
            let cal = NSCalendar.currentCalendar()
            if cal.isDateInToday(date) {
                let sec = NSDate().timeIntervalSinceDate(date)
                if sec < 60 {
                    return "刚刚"
                } else if sec < 60*60 {
                    return "\(Int(sec/60))分钟前"
                } else {
                    return "\(Int(sec/3600))小时前"
                }
            } else if cal.isDateInYesterday(date) {
                dateFormatter.dateFormat = "昨天 HH:mm"
                return dateFormatter.stringFromDate(date)
            } else {
                dateFormatter.dateFormat = "MM月dd日 HH:mm"
                return dateFormatter.stringFromDate(date)
            }
        } else {
            dateFormatter.dateFormat = "yyyy年MM月dd日 HH:mm"
            return dateFormatter.stringFromDate(date)
        }
    }
    
     /// 微博ID
    var id: Int64 = 0
    
     /// 微博信息内容
    var text: String? {
        didSet {
            textAttr = self.getTextAttr(text ?? "")
        }
    }
    
     /// 微博表情信息内容
    var textAttr: NSMutableAttributedString?
    
     /// 微博来源
    var source: String? {
        didSet {
            guard var str = source where str.containsString("\">") else {
                sourceStr = NSMutableAttributedString(string: "")
                return
            }
            
            let start = str.rangeOfString("\">")
            let end = str.rangeOfString("</a>")
            
            str = str.substringWithRange((start?.endIndex)!..<((end?.startIndex) ?? (start?.endIndex)!))
            
            str = "来自 \(str)"
            
            let AttStr = NSMutableAttributedString(string: str)
            
            let rang = (str as NSString).rangeOfString("来自")
            
            AttStr.addAttributes([NSForegroundColorAttributeName : APPTintColor], range: rang)
            
            sourceStr = AttStr
        }
    }
    
    var sourceStr: NSMutableAttributedString?
    
    var user: WBFristUserInforModel?
    
    var retweeted_status: WBFristPageDataModel?
    
    var pic_urls: [WBFristPagePictureModel]?

    /// 转发数
    var reposts_count: Int = 0 {
        didSet {
            repostStr = getTabbarButtonTitle("转发", count: reposts_count)
        }
    }
    
    var repostStr: String?
    
    /// 评论数
    var comments_count: Int = 0 {
        didSet {
            commentStr = getTabbarButtonTitle("评论", count: comments_count)
        }
    }

    var commentStr: String?
    
    /// 表态数
    var attitudes_count: Int = 0 {
        didSet {
            attitudeStr = getTabbarButtonTitle("赞", count: attitudes_count)
        }
    }
    
    var attitudeStr: String?

    init(dic: [String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dic)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            guard let dic = value as? [String:AnyObject] else {
                return
            }
            
            user = WBFristUserInforModel(dic: dic)
        } else if key == "retweeted_status" {
            guard let dic = value as? [String:AnyObject] else {
                return
            }
            
            retweeted_status = WBFristPageDataModel(dic: dic)
        } else if key == "pic_urls" {
            guard let arr = value as? [[String:AnyObject]] else {
                return
            }
            
            pic_urls = [WBFristPagePictureModel]()
            for dic in arr {
                pic_urls?.append(WBFristPagePictureModel(dic: dic))
            }
        } else {
            super.setValue(value, forKey: key)
        }
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    private func getTextAttr(text: String) -> NSMutableAttributedString {
        let textStr = NSMutableAttributedString(string: text)
        
        var regexResults: [WBRegexResult] = [WBRegexResult]()
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, string, range, _) in
            regexResults.append(WBRegexResult(str: string.memory as! String, ran: range.memory))
        }
        
        for regexResult in regexResults.reverse() {
            let imageName = WBEmoticonsBundle.shareEmoticonsBundle.searchEmoticonsPngName(regexResult.string) ?? ""
            
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: imageName, inBundle: WBEmoticonsBundle.shareEmoticonsBundle.bundle, compatibleWithTraitCollection: nil)
            
            let textHeight = UIFont.systemFontOfSize(15).lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: textHeight, height: textHeight)
            
            let attStr = NSAttributedString(attachment: attachment)
            textStr.replaceCharactersInRange(regexResult.range, withAttributedString: attStr)
        }
        
        return textStr
    }
    
    private func getTabbarButtonTitle(title: String, count: Int) -> String {
        if count > 0 {
            if count < 10000 {
                return " \(count)"
            } else {
                let countF = CGFloat(count / 1000) / 10
                var str = "\(countF)"
                
                if str.containsString(".0") {
                    str = str.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                
                return " \(str)万"
            }
        } else {
            return " \(title)"
        }
    }
    
    override var description: String {
        let key = ["created_at", "id", "text", "source"]
        
        return dictionaryWithValuesForKeys(key).description
    }
    
}
